package com.gadgets.busi.bm01.task;

import com.gadgets.busi.bm01.common.GadgetsBm01Constant;
import com.gadgets.busi.bm01.common.event.GadgetsBm01HttpFinishEvent;
import com.gadgets.busi.bm01.common.event.GadgetsBm01TaskFileEvent;
import com.gadgets.busi.bm01.common.event.GadgetsBm01TaskFinishEvent;
import com.gadgets.busi.bm01.common.event.GadgetsBm01TaskStartEvent;
import com.gadgets.framework.common.constant.GadgetsConstant;
import com.gadgets.framework.common.util.*;
import com.gadgets.framework.thread.task.AbstractRunnable;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;

import java.util.List;

/**
 * The type Copy 1024 txt runnable.
 *
 * @author UncleXiu
 * @version V1.0.0
 * @data 2020 -09-21
 */
public class Copy1024TxtRunnable extends AbstractRunnable {

    /**
     * 文件名
     */
    private String title;
    /**
     * 网站根地址
     */
    private String targetSite;
    /**
     * 文本地址相对路径
     */
    private String[] path;
    /**
     * 写入地址
     */
    private String writePath;
    /**
     * 当前执行百分比
     */
    private double percent = 0.0;
    /**
     * 拷贝模式
     */
    private String copyModuel;

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        GadgetsBm01TaskFinishEvent finishEvent = SpringUtils.getBeanByName(GadgetsBm01Constant.EVENT_LIST.BM01_TASK_FINISH_EVENT,GadgetsBm01TaskFinishEvent.class);
        finishEvent.setTaskNo(getTaskNo());
        if(StringUtils.isBlank(copyModuel)){
            logger.error("拷贝模式字段为空，不能执行任务");
            finishEvent.setSuccessFlag(GadgetsConstant.NUMBER_CONSTANT.STR_NUMBER_0);
            return;
        }
        try {
            logger.info("线程任务Copy1024SingleTxtRunnable已启动，任务号{}",getTaskNo());
            // 发布任务启动事件
            GadgetsBm01TaskStartEvent startEvent = SpringUtils.getBeanByName(GadgetsBm01Constant.EVENT_LIST.BM01_TASK_START_EVENT,GadgetsBm01TaskStartEvent.class);
            startEvent.setTaskNo(getTaskNo());
            ThreadTaskUtil.publishEvent(startEvent);
            double excutePercent = 100.0 /path.length;
            for (String extPath : path) {
                String targetPath = targetSite + "/" + extPath;
                logger.info("拷贝路径：{}",targetPath);
                // 开始解析路径
                String html = HttpClientUtil.requestHttpByGetMethodForTxt(GadgetsBm01Constant.HTTP_REQUEST_HEAD.head1024Map,targetPath,"UTF-8");
                // 发布HTTP请求完成事件，更新任务进度
                percent = percent + excutePercent*0.7;
                GadgetsBm01HttpFinishEvent httpFinishEvent = SpringUtils.getBeanByName(GadgetsBm01Constant.EVENT_LIST.BM01_TASK_HTTP_REQUEST_FINISH_EVENT,GadgetsBm01HttpFinishEvent.class);
                httpFinishEvent.setTaskNo(getTaskNo());
                httpFinishEvent.setPercent(percent);
                ThreadTaskUtil.publishEvent(httpFinishEvent);
                // 解析HTML文本
                if(!StringUtils.isBlank(html)) {
                    Document document = Jsoup.parse(html);
                    // 获取文本内容
                    Element textElement = document.select("div#read_tpc").first();
                    List<TextNode> nodeList = textElement.textNodes();
                    StringBuilder builder = new StringBuilder();
                    if(null!=nodeList && nodeList.size()>0){
                        // 场景1：直接div内写文本
                        for (TextNode textNode : nodeList) {
                            builder.append(textNode.text()).append("\n");
                        }
                    }else{
                        // 场景2：存在某些以span包裹文本的格式
                        Elements elements = textElement.select("font>span>span");
                        if(null!=elements){
                            for (Element element : elements) {
                                builder.append(element.text()).append("\n");
                            }
                        }
                    }
                    String artical = builder.toString();
                    // 获取文件名
                    if(GadgetsBm01Constant.COPY_MODUEL.SINGLE_COPY.equals(copyModuel)){
                        Element tpcSpanElement = document.select("span#subject_tpc").first();
                        title = tpcSpanElement.text();
                    }
                    logger.info("文件名：{}",new Object[]{title});
                    String targetFile = writePath+"/"+title+".txt";
                    logger.info("文本写入文件：{}",targetFile);
                    FileOperUtil.writeTxtTotFile(targetFile,artical);
                    // 发布文件写入完成事件，更新文件路径
                    GadgetsBm01TaskFileEvent fileEvent = SpringUtils.getBeanByName(GadgetsBm01Constant.EVENT_LIST.BM01_TASK_FILE_WRITE_EVENT, GadgetsBm01TaskFileEvent.class);
                    fileEvent.setTaskFilePath(targetFile);
                    ThreadTaskUtil.publishEvent(fileEvent);
                    // 发布HTTP请求完成事件，更新任务进度
                    percent = percent + excutePercent*0.3;
                    finishEvent.setPercent(percent);
                    finishEvent.setSuccessFlag(GadgetsConstant.NUMBER_CONSTANT.STR_NUMBER_1);
                    logger.info("文本写入文件完成：{}",targetFile);
                }else {
                    logger.warn("HTTP没有返回HTML文本");
                }
            }
            logger.info("线程任务Copy1024SingleTxtRunnable已完成，任务号{}",getTaskNo());
        } catch (Throwable e) {
            logger.error(StringUtils.formatExceptionStack(e));
            finishEvent.setPercent(percent);
            finishEvent.setSuccessFlag(GadgetsConstant.NUMBER_CONSTANT.STR_NUMBER_0);
        }
        // 发布任务完成事件
        ThreadTaskUtil.publishEvent(finishEvent);
        taskFinish();
    }

    /**
     * Gets target site.
     *
     * @return the target site
     */
    public String getTargetSite() {
        return targetSite;
    }

    /**
     * Sets target site.
     *
     * @param targetSite the target site
     */
    public void setTargetSite(String targetSite) {
        this.targetSite = targetSite;
    }

    /**
     * Get path string [ ].
     *
     * @return the string [ ]
     */
    public String[] getPath() {
        return path;
    }

    /**
     * Sets path.
     *
     * @param path the path
     */
    public void setPath(String[] path) {
        this.path = path;
    }

    /**
     * Gets write path.
     *
     * @return the write path
     */
    public String getWritePath() {
        return writePath;
    }

    /**
     * Sets write path.
     *
     * @param writePath the write path
     */
    public void setWritePath(String writePath) {
        this.writePath = writePath;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getCopyModuel() {
        return copyModuel;
    }

    public void setCopyModuel(String copyModuel) {
        this.copyModuel = copyModuel;
    }
}
